﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
using TA.JSON;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Panel which can render its contents and output them to the client asynchronously.
	/// </summary>
	public class UpdatePanel : Panel, IJsonSerializable
	{

		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public UpdatePanel()
		{
		}
		#endregion
		#region EVENTS
		#endregion
		#region PROPS
		#endregion
		#region METHODS
		/// <summary>
		/// Renders and returns the HTML markup of this panel's children.
		/// </summary>
		/// <returns></returns>
		public string GetContent()
		{
			using (StringWriter sw = new StringWriter())
			{
				using (HtmlTextWriter htw = new HtmlTextWriter(sw))
				{
					this.RenderChildren(htw);
					return sw.ToString();
				}
			}
		}
		#endregion
		#region JSON
		/// <summary>
		/// Gets true.
		/// </summary>
		public bool IsDirty
		{
			get { return true; }
		}
		/// <summary>
		/// Serializes this UpdatePanel, outputting ID, markup and script as properties.
		/// </summary>
		/// <param name="jw"></param>
		public void Serialize(JsonWriter jw)
		{
			this.SerializeObject(jw);
		}
		/// <summary>
		/// SerializeContents.
		/// </summary>
		/// <param name="jw"></param>
		public void SerializeContents(JsonWriter jw)
		{
			string html = this.GetContent();
			Dictionary<string, BaseInclude> includes = new Dictionary<string, BaseInclude>();
			IncludeCollection ic = new IncludeCollection();
			this.ForEachRecursive<TControl>(delegate(TControl ctl)
			{
				ic.Clear();
				ctl.RegisterIncludes(ic);
				foreach (BaseInclude one in ic.Values)
				{
					if (!includes.ContainsKey(one.FileName) && !this.TPage.AllIncludes.ContainsKey(one.FileName))
						includes[one.FileName] = one;
				}

			});

			jw.PropertyName("I");
			jw.Value(this.ClientID);


			jw.PropertyName("M");
			jw.Value(HtmlTools.GetMarkup(html), true);

			jw.PropertyName("S");
			jw.Value(HtmlTools.GetScript(html), true);

			jw.PropertyName("C");
			jw.StartArray();
			foreach (BaseInclude oneInclude in includes.Values)
			{
				oneInclude.Serialize(jw);
			}
			jw.EndArray();
		}

		#endregion
		#endregion
		#region INTERNAL
		#region CONST/STATIC
		#endregion
		#region VARS
		#endregion
		#region PROPS
		#endregion
		#region METHODS
		#region INIT
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			this.TPage.Includes.Add(Script.ResponseUpdatePanel);
		}
		#endregion
		#region DATA
		#endregion
		#region HANDLERS
		#endregion
		#endregion
		#endregion				
				

	}
}
